<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>sockjs test</title>
  <script src="js/sockjs.js"></script>
</head>

<body>
  <h1>WS Chat</h1>
  <div id="chat">
    <p><em>Connecting...</em></p>
  </div>
  <input type="text" id="input_content" />
  <button type="button" id="submit">Submit</button>
  <script>
    const chat = document.getElementById("chat");
    const input_content = document.getElementById("input_content");
    const submit = document.getElementById("submit");

    // var sock = new SockJS('http://127.0.0.1:9001/chat');
    // sock.onopen = function () {
    // 	// console.log('open');
    // 	// sock.send('test');
    // 	chat.innerHTML = "<p><em>Connected!</em></p>";
    // };

    // sock.onmessage = function (e) {
    // 	// console.log('message', e.data);
    // 	// sock.close();
    // 	showMessage(msg.data);
    // 	showMessage(msg.data);
    // };

    // sock.onclose = function () {
    // 	// console.log('close');
    // 	showMessage("Disconnected!");
    // };

    const ws = new WebSocket("ws://127.0.0.1:9001/ws");

    ws.onopen = function () {
      chat.innerHTML = "<p><em>Connected!</em></p>";
    };

    ws.onmessage = function (msg) {
      // showMessage(msg.data);
      showMessage(msg.data);
    };

    ws.onclose = function () {
      showMessage("Disconnected!");
    };

    submit.onclick = function () {
      const msg = input_content.value;
      ws.send(msg);
      input_content.value = "";
      showMessage("<You>: " + msg);
    };
    function showMessage(data) {
      const line = document.createElement("p");
      line.innerText = data;
      chat.appendChild(line);
    }
  </script>
</body>

</html>
